const blueDeviceService = require('../services/blue-device-manger');
const { logger } = require('./logger');

const authenticateSerial = async (req, res, next) => {
    const serial = req.headers['x-serial-key'];

    if (!serial) {
        logger.warn('请求缺少序列号', {
            ip: req.ip,
            url: req.url,
            method: req.method
        });
        return res.status(401).json({
            error: 'Serial key is required',
            message: '请求头中必须包含 x-serial-key'
        });
    }

    try {
        // 从数据库验证设备
        const device = await blueDeviceService.validateDevice(serial);

        if (!device) {
            logger.warn('无效的序列号', {
                serial,
                ip: req.ip,
                url: req.url,
                method: req.method
            });
            return res.status(403).json({
                error: 'Invalid serial key',
                message: '无效的设备序列号或设备未激活'
            });
        }

        // 将设备信息添加到请求对象中，供后续使用
        req.device = device;

        logger.info('设备认证成功', {
            macAddress: device.macAddress,
            deviceName: device.deviceName,
            ip: req.ip,
            url: req.url,
            method: req.method
        });

        next();
    } catch (error) {
        logger.error('设备认证过程出错', {
            error: error.message,
            serial,
            ip: req.ip,
            url: req.url,
            method: req.method
        });

        return res.status(500).json({
            error: 'Authentication error',
            message: '认证过程出现错误，请稍后重试'
        });
    }
};

module.exports = {
    authenticateSerial
};